<template>
	<div class="system_user_wrapper">
		<el-tree
			class="depart"
			ref="tree"
			node-key="id"
			:data="departTree"
			:props="defaultProps"
			highlight-current
			:expand-on-click-node="false"
			@node-click="handleDepartTree"
		></el-tree>
		<sw-common-frame class="user" :loading="loading">
			<template slot="button">
				<el-button size="small" type="primary" icon="el-icon-plus" @click="handleOpenDialog()">新增</el-button>
				<template v-if="selectedUser.length > 0">
					<el-button size="small" type="danger" icon="el-icon-delete" plain @click="handleBatchDelete()">批量删除</el-button>
				</template>
			</template>
			<template slot="query">
				<el-form size="small" inline>
					<el-form-item>
						<el-input v-model="queryData.userName" clearable placeholder="用户姓名" style="width: 180px"></el-input>
					</el-form-item>
					<el-form-item>
						<el-input v-model="queryData.account" clearable placeholder="用户账号" style="width: 180px"></el-input>
					</el-form-item>
					<el-form-item>
						<el-select v-model="queryData.type" clearable placeholder="用户类型" style="width: 100px">
							<el-option v-for="(item, index) in dictEnums['USER_TYPE']" :key="index" :label="item.msg" :value="item.value"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" icon="el-icon-search" @click="queryTableData()">查询</el-button>
					</el-form-item>
				</el-form>
			</template>
			<template slot="table">
				<el-table size="medium" ref="table" :data="tableData" stripe height="100%" @selection-change="handleSelectionChange">
					<el-table-column type="selection" width="48" align="center"></el-table-column>
					<el-table-column label="用户姓名/账号" min-width="160" :formatter="returnUserAccount"></el-table-column>
					<el-table-column label="用户类型" min-width="80" :formatter="returnUserType"></el-table-column>
					<el-table-column prop="deptName" label="用户院系" min-width="150" show-overflow-tooltip></el-table-column>
					<el-table-column label="状态" min-width="70" :formatter="returnUserStatus"></el-table-column>
					<el-table-column prop="createName" label="创建者" min-width="100"></el-table-column>
					<el-table-column label="创建时间" min-width="110" :formatter="returnCreateTime"></el-table-column>
					<el-table-column label="操作" width="150">
						<template slot-scope="{ row }">
							<el-button size="medium" type="text" @click="handleOpenDialog(row)">编辑</el-button>
							<el-button size="medium" type="text" @click="handleDeleteData(row)">删除</el-button>
							<el-dropdown class="dropdown" trigger="click" @command="handleUserCommand">
								<el-button size="medium" type="text">
									更多
									<i class="el-icon-arrow-down"></i>
								</el-button>
								<el-dropdown-menu slot="dropdown">
									<el-dropdown-item :command="{ type: 'blockedAccount', row }" v-if="row.del === '1'">封禁账号</el-dropdown-item>
									<el-dropdown-item :command="{ type: 'recoverAccount', row }" v-if="row.del === '2'">恢复账号</el-dropdown-item>
									<el-dropdown-item :command="{ type: 'updatePassword', row }">更改密码</el-dropdown-item>
									<el-dropdown-item :command="{ type: 'configRole', row }">配置角色</el-dropdown-item>
								</el-dropdown-menu>
							</el-dropdown>
						</template>
					</el-table-column>
				</el-table>
			</template>
			<template slot="page">
				<sw-pagination :total="dataCount" :page.sync="queryData.page" :limit.sync="queryData.limit" @change="queryTableData()"></sw-pagination>
			</template>
			<form-dialog v-model="formDialog" :data-id="dataId" @refresh="queryTableData()"></form-dialog>
			<config-role v-model="configDialog" :data-id="dataId"></config-role>
		</sw-common-frame>
	</div>
</template>

<script>
import moment from 'moment';
import formDialog from './form';
import { mapGetters } from 'vuex';
import configRole from './configRole';
import systemMixins from '@/views/common/systemMixins';
import { getUserList, deleteUser, banAndRecoveryUser } from '@/api/system/tbSysUser';
export default {
	mixins: [systemMixins],
	components: { formDialog, configRole },
	data() {
		return {
			defaultProps: { label: 'name', children: 'childList' },
			configDialog: false,
			selectedUser: []
		};
	},
	computed: {
		...mapGetters(['dictEnums', 'departTree'])
	},
	methods: {
		//获取用户数据
		async getTableData() {
			let params = { ...this.queryData };
			let result = await getUserList(params).then((res) => res.data);
			if (result.code === '0') {
				this.dataCount = parseInt(result.count);
				this.tableData = result.data || [];
			}
		},

		handleDepartTree(data, node) {
			if (!!this.queryData.deptId && this.queryData.deptId === data.id) {
				this.$delete(this.queryData, 'deptId');
				this.$nextTick(() => {
					this.$refs['tree'].setCurrentKey(null);
				});
			} else {
				this.$set(this.queryData, 'deptId', data.id);
			}
			this.queryTableData();
		},

		//删除用户数据
		handleDeleteData(data) {
			this.handleDeleteFunction([data.id], data.userName, '用户');
		},

		//批量删除数据
		handleBatchDelete() {
			let idArr = this.selectedUser.map((item) => item.id);
			let nameArr = this.selectedUser.map((item) => item.userName);
			this.handleDeleteFunction(idArr, nameArr, '用户');
		},

		//删除数据请求
		async deleteDataRequest(params) {
			let result = await deleteUser(params).then((res) => res.data);
			if (result.code === 0) {
				this.$message.success('删除用户成功');
			}
		},

		//更多操作
		handleUserCommand({ type, row }) {
			if (type === 'blockedAccount') {
				this.banAndRecoveryRequest(row.id, 2);
			}
			if (type === 'recoverAccount') {
				this.banAndRecoveryRequest(row.id, 1);
			}
			if (type === 'updatePassword') {
				this.$bus.$emit('updatePassword', row.id);
			}
			if (type === 'configRole') {
				this.configDialog = true;
				this.dataId = row.id;
			}
		},

		//封禁/恢复请求
		async banAndRecoveryRequest(id, del) {
			let params = { id, canUpdate: 1, del };
			let result = await banAndRecoveryUser(params).then((res) => res.data);
			if (result.code === 0) {
				let messageText = (() => {
					if (del === 1) {
						return '恢复';
					} else if (del === 2) {
						return '封禁';
					}
				})();
				this.$message.success(`${messageText}账号成功`);
				this.queryTableData();
			}
		},

		//选中数据项
		handleSelectionChange(selection) {
			this.selectedUser = [...selection];
		},

		//格式化用户姓名账号
		returnUserAccount(data) {
			return [
				this.$createElement('span', { style: { marginRight: '10px', whiteSpace: 'nowrap' } }, data.userName),
				this.$createElement('span', { style: { marginRight: '10px', whiteSpace: 'nowrap' } }, data.account)
			];
		},

		//格式化用户类型
		returnUserType(data) {
			let info = this.dictEnums['USER_TYPE'].find((n) => n.value === data.type);
			if (data.type === '1') {
				return this.$createElement('elTag', { attrs: { size: 'medium', type: 'warning' } }, info.msg);
			} else if (data.type === '2') {
				return this.$createElement('elTag', { attrs: { size: 'medium', type: 'success' } }, info.msg);
			}
		},

		//格式化用户状态
		returnUserStatus(data) {
			if (data.del === '1') {
				return this.$createElement('elTag', { attrs: { size: 'medium', type: 'success' } }, '正常');
			} else if (data.del === '2') {
				return this.$createElement('elTag', { attrs: { size: 'medium', type: 'danger' } }, '封禁');
			}
		},

		//格式化创建时间
		returnCreateTime(data) {
			let momentTime = moment(data.createTime);
			return [
				this.$createElement('span', { style: { marginRight: '10px', whiteSpace: 'nowrap' } }, momentTime.format('YYYY-MM-DD')),
				this.$createElement('span', { style: { marginRight: '10px', whiteSpace: 'nowrap' } }, momentTime.format('HH:mm:ss'))
			];
		}
	}
};
</script>
<style lang="scss" scoped>
.system_user_wrapper {
	display: flex;
	height: 100%;
	overflow: hidden;
	.depart {
		width: 20%;
		min-width: 210px;
		flex-shrink: 0;
		padding: 8px 0;
		overflow: auto;
		border-right: solid 1px #ebeef5;
	}
	.user {
		flex: 1;
	}
}
</style>
